"use client"
import { useState, useEffect } from 'react';
import Web3 from 'web3';
import { ethers } from 'ethers';

export default function WalletConnector() {
  const [account, setAccount] = useState(null);
  const [balance, setBalance] = useState(null);
  const [chainId, setChainId] = useState(null);
  const [error, setError] = useState(null);
  const [signature, setSignature] = useState('');
  // const connectWallet = async () => {
  //   if (typeof window.ethereum !== 'undefined') {
  //     try {
  //       const web3 = new Web3(window.ethereum);
  //       // 请求用户授权并获取账户地址
  //       const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });

  //       if (accounts.length === 0) {
  //         throw new Error('No accounts found');
  //       }

  //       const address = accounts[0];
  //       setAccount(address);

  //       // 获取余额
  //       const balance = await web3.eth.getBalance(address);
  //       console.log(balance);

  //       setBalance(web3.utils.fromWei(balance, 'ether'));

  //       // 获取链 ID
  //       const chainId = await web3.eth.getChainId();
  //       console.log(chainId);


  //       setChainId(chainId);

  //       setError(null); // 清除错误信息
  //     } catch (error) {
  //       console.error('Error connecting to wallet:', error);
  //       setError(error.message);
  //     }
  //   } else {
  //     alert('MetaMask is not installed');
  //   }
  // };


  let web3;
  let userAccount;
  let transactionId;

  async function connectWallet() {
    if (typeof window.ethereum !== 'undefined') {
      web3 = new Web3(window.ethereum);
    } else {
      alert('MetaMask未安装!');
    }

    if (typeof window.ethereum !== 'undefined') {
      try {
        // 请求账户访问
        await window.ethereum.request({ method: 'eth_requestAccounts' });

        // 尝试切换到Sepolia测试网
        try {
          await window.ethereum.request({
            method: 'wallet_switchEthereumChain',
            params: [{ chainId: '0xaa36a7' }] // Sepolia的Chain ID是11155111，十六进制为0xaa36a7
          });
          console.log('Successfully switched to Sepolia network');

        } catch (switchError) {
          // 这个错误代码表明该网络还没有被添加到MetaMask
          if (switchError.code === 4902) {
            try {
              await window.ethereum.request({
                method: 'wallet_addEthereumChain',
                params: [{
                  chainId: '0xaa36a7',
                  chainName: 'Sepolia Test Network',
                  rpcUrls: ['https://rpc.sepolia.org'], // 替换为有效的Sepolia RPC URL
                  nativeCurrency: {
                    name: 'Sepolia ETH',
                    symbol: 'ETH',
                    decimals: 18
                  },
                  blockExplorerUrls: ['https://sepolia.etherscan.io'] // 替换为有效的区块浏览器URL
                }]
              });
              console.log('Successfully added and switched to Sepolia network');
            } catch (addError) {
              console.error('Failed to add Sepolia network', addError);
            }
          } else {
            console.error('Failed to switch to Sepolia network', switchError);
          }
        }
      } catch (error) {
        console.error('User rejected the request', error);
      }
      try {
        await window.ethereum.request({ method: 'eth_requestAccounts' });
        userAccount = (await web3.eth.getAccounts())[0];
      } catch (error) {
        console.error('连接MetaMask失败:', error);
      }
    } else {
      console.log('MetaMask is not installed. Please install it to use this feature.');
    }
  }

  async function sendPayment() {
    const toAddress = '0x18eb40AaFfAE9320EC317FFa37100449e3171C67';
    const amountInEther = '0.0001'; // 发送0.01 ETH

    const transactionParameters = {
      from: userAccount,
      to: '0x18eb40AaFfAE9320EC317FFa37100449e3171C67', // 替换为接收方地址
      value: '0x' + (0.001 * 10 ** 18).toString(16), // 0.001 ETH, 转换为十六进制
      // gasPrice: '0x09184e72a000', // 替换为合适的Gas Price
      // gas: '0x2710', // 替换为合适的Gas Limit
    };
    console.log(transactionParameters);

    // 发送交易
    try {
      const txHash = await window.ethereum.request({
        method: 'eth_sendTransaction',
        params: [transactionParameters],
      });
      transactionId = txHash;
      console.log('Transaction sent with hash:', txHash);
    } catch (sendError) {
      console.error('Failed to send transaction', sendError);
    }
  }

  async function tran() {
    const transaction = await web3.eth.getTransaction(transactionId);
    console.log('Transaction details:' + transaction);
    console.log(transaction);
    if (transaction.blockHash != undefined) {
      alert("交易成功");
    } else {
      alert("交易不成功");
    }
  }
  async function signMessage() {
    //const provider = new ethers.providers.Web3Provider(window.ethereum);
    const accounts = await web3.eth.getAccounts();
    setAccount(accounts[0]);
    const message = 'Hello,sign this message!';
    const signedMessage = await web3.eth.personal.sign(message, accounts[0], '');
    setSignature(signedMessage);
    console.log(signedMessage);
  }
  const verifyMessage = async () => {
    const recoveredAddress = web3.eth.accounts.recover('Hello,sign this message!', "0xa201a04439139169742a5d9de3700f91e8623ef18a850853738dc76c65f15506436162f49a1d9375d95bafe3ea6bebc070dd997d1a8105856a3f84518010476d1b");
    console.log(recoveredAddress);
    

  };


  return (
    <div>
      <button onClick={connectWallet}>Connect MetaMask</button>
      <button onClick={sendPayment}>sendPayment</button>
      <button onClick={tran}>getTran</button>
      <button onClick={signMessage}>signMessage</button>
      <button onClick={verifyMessage}>test</button>
      <div>message: {signature}</div>
      {account && <p>Connected account: {account}</p>}
      {balance && <p>Balance: {balance} ETH</p>}
      {chainId && <p>Chain ID: {chainId}</p>}
      {error && <p style={{ color: 'red' }}>Error: {error}</p>}
    </div>
  );
}

